use regex::{Captures, Regex};

pub fn use_position_arg(
  arg_list: &Vec<String>, 
  origin_text: &str
) -> (String, Vec<usize>) {
    let exp = Regex::new(r"\$\{(:*)(\d+)\}").expect("无法生成正则表达式");
    let mut exclude_index_list = Vec::<usize>::new();
    let result_cmd = exp.replacen(origin_text, 0, |caps: &Captures| {
        let colon_capture = &caps[1];
        if !colon_capture.is_empty() {
            let colon_result: &str = &colon_capture[1..];
            return format!("${{{}}}", format!("{}{}", colon_result, &caps[2]));
        }
        let parse_u8 = String::from(&caps[2]).parse::<usize>();
        match parse_u8 {
            Ok(index) => {
                if index == 0 {
                    panic!("index start from 1 not 0");
                }
                let target_index = index - 1;
                if target_index < arg_list.len() {
                    let target_arg = arg_list.iter().nth(target_index).unwrap();
                    exclude_index_list.push(target_index);
                    return String::from(target_arg);
                }
                return String::new();
            }
            Err(_) => {
                return String::new();
            }
        }
    });
    (result_cmd.to_string(), exclude_index_list)
}

pub fn use_remain_arg(
    remain_arg_txt: &str,
    origin_text: &str
) -> String {
    let exp = Regex::new(r"\$\{(:*)(\.{3})\}").expect("无法生成正则表达式");
    let result_cmd = exp.replacen(origin_text, 0, |caps: &Captures| {
        let colon_capture = &caps[1];
        if !colon_capture.is_empty() {
            let colon_result: &str = &colon_capture[1..];
            return format!("${{{}}}", format!("{}{}", colon_result, &caps[2]));
        }
        return String::from(remain_arg_txt);
    });
    result_cmd.to_string()
}
